package com.cn.longdistancebusstation.personal;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.BuildConfig;
import com.cn.longdistancebusstation.MainActivity;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.Version;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.support.v4.content.FileProvider.getUriForFile;

/**
 * Created by mucheng on 2018/2/25.
 */

public class AboutActivity extends BaseActivity implements View.OnClickListener{
    private TextView mCurrentUpdateCodeTextView;
    private Button mUpdateVersionButton;
    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;
    private ProgressBar mProgressBar;
    private Context mContext;
    private String mCurrentVersionNumString;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about_us);
        getTitleTextView().setText("关于");
        initView();
        getPersimmions();
    }

    private void initView() {
        mCurrentUpdateCodeTextView=(TextView)findViewById(R.id.current_version_code);
        mUpdateVersionButton=(Button)findViewById(R.id.btn_update_version);
        mUpdateVersionButton.setOnClickListener(this);
        //
        try
        {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            mCurrentUpdateCodeTextView.setText(packageInfo.versionName);
        }
        catch(PackageManager.NameNotFoundException e)
        {
        }
    }
    @TargetApi(Build.VERSION_CODES.M)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.INTERNET);
            }
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取路径状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }
    @TargetApi(Build.VERSION_CODES.M)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.btn_update_version:
                updateVersion();
                break;
        }

    }

    private void updateVersion() {
        showHud();
        PackageManager packageManager = getPackageManager();
        try
        {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.SERVER_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            HttpService httpService = retrofit.create(HttpService.class);
            Call<Result<Version>> call = httpService.getVersionInfo(packageInfo.versionCode);
            call.enqueue(new Callback<Result<Version>>() {
                @Override
                public void onResponse(Call<Result<Version>> call, Response<Result<Version>> response) {
                    hideHud();
                    Result<Version> result = response.body();
                    if(result.getHead().getSuccess()){
                        //有新版本,弹出提示框询问是否更新
                        final Version version = result.getBody();
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(AboutActivity.this);
                        StringBuilder strHint = new StringBuilder("有新版本，是否更新?");
                        if(version.getRemark().length()>0){
                            strHint.append("本次更新内容如下:\n");
                            strHint.append(version.getRemark());
                        }
                        dialogBuilder.setMessage(strHint);
                        dialogBuilder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //开始下载
                                downloadFile(BuildConfig.SERVER_URL+version.getAPKPath());
                            }
                        });
                        dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //取消，什么都不需要做
                            }
                        });
                        Dialog dialog = dialogBuilder.show();
                        dialog.setCanceledOnTouchOutside(false);
                    }
                    else{
                        Toast.makeText(AboutActivity.this, result.getHead().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Result<Version>> call, Throwable t) {
                    hideHud();
                    Toast.makeText(AboutActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

                }
            });
        }
        catch(PackageManager.NameNotFoundException e)
        {}

    }

    private void downloadFile(final String fileURL){
        Log.d("路径",fileURL);
        //创建进度条
        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(AboutActivity.this);
        View view = View.inflate(AboutActivity.this, R.layout.download_file_progress, null);
        mProgressBar = (ProgressBar)view.findViewById(R.id.progressBar);
        mProgressBar.setMax(100);
        final TextView percentTextView = (TextView)view.findViewById(R.id.textView_hint);
        dialogBuilder.setView(view);
        final Dialog dialog = dialogBuilder.show();
        dialog.setCanceledOnTouchOutside(false);

        Thread thread = new Thread(new Runnable() {
            int writeDataSize = 0;
            @Override
            public void run() {
                try
                {
                    OkHttpClient httpClient = new OkHttpClient();
                    Request request =  new Request.Builder().url(fileURL).build();
                    okhttp3.Response response = httpClient.newCall(request).execute();
                    if(response.isSuccessful()){
                        final long fileSize = response.body().contentLength();
                        String savePath = Environment.getExternalStorageDirectory() + "/sdbusstation/";
                        Log.d("存储",savePath);
                        File file = new File(savePath+"sdbusstation.apk");
                        if(file.exists()){
                        }
                        else{
                            new File(savePath).mkdir();
                            file.createNewFile();
                        }
                        InputStream inputStream = response.body().byteStream();
                        FileOutputStream outputStream = new FileOutputStream(file);
                        byte[] bytes = new byte[10240];
                        int length;
                        while((length=inputStream.read(bytes)) != -1){
                            outputStream.write(bytes, 0, length);
                            outputStream.flush();
                            writeDataSize += length;
                            final long totalWriteSize = writeDataSize;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    int percent = (int) (totalWriteSize/(float)fileSize*100);
                                    mProgressBar.setProgress(percent);
                                    percentTextView.setText("正在下载:" + percent+"% / 100%");
                                }
                            });
                        }
                        dialog.dismiss();
                        installApk(file);
                    }
                }
                catch(IOException e)
                {
                    String strHint = e.getMessage();
                    Log.i("MainActivity", "");
                    dialog.dismiss();
                }
            }
        });
        thread.start();
        //
    }
    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

            return false;
        }

        return true;
    }


    private void installApk(File file) {
        if(!isGrantExternalRW(this)){
            return;
        }

        //调用系统安装程序
//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.VIEW");
//        intent.addCategory("android.intent.category.DEFAULT");
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//        startActivity(intent);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            // 第二个参数,即第一步中配置的authorities
            Uri contentUri = getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", file);
            // 声明需要的临时权限
//            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }
        startActivity(intent);

    }
}
